<?php

/* * ****************************************************************************
 * controllers\UserController
 * 
 * author  Laureta Xhaferaj
 * email   laureta@first.al
 * 
 * @function index
 * @function create
 * @function store
 * @function show
 * @function edit
 * @function destroy
 * @function doLogin
 * @function doLogout
 * @function loginWithGoogle
 * @function edit_roles
 * @function update_roles
 * @function pending_users
 * @function users_roles
 * *************************************************************************** */

class UserController extends \BaseController {

    public function __construct() {
        $this->beforeFilter('csrf', array('on' => 'post'));
    }

    /**
     * Display login page.
     *
     * @return Response
     */
    public function index() {
        return View::make('pages.login');
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return Response
     */
    public function create() {
        
    }

    /**
     * Store a new user registered.
     *
     * @return Response
     */
    public function store() {
        Input::flash();
        $data = [
            "errors" => null
        ];
        $attributes = array(
            'firstname' => Lang::get('login.first_name'),
            'username' => Lang::get('login.username'),
            'lastname' => Lang::get('login.last_name'),
            'email' => Lang::get('login.email'),
            'password' => Lang::get('login.password'),
            'password_confirmation' => Lang::get('login.confirm_password'),
        );
        $rules = array(
            'firstname' => 'required|alpha|min:2',
            'username' => 'required|alpha|min:2',
            'lastname' => 'required|alpha|min:2',
            'email' => 'required|email|unique:users',
            'password' => 'required|alpha_num|between:6,12|confirmed',
            'password_confirmation' => 'required|alpha_num|between:6,12'
        );
        $validation = Validator::make(Input::all(), $rules, array(), $attributes);
        if ($validation->passes()) {
            $data = new User;
            $data->Username = Input::get('username');
            $data->email = Input::get('email');
            $data->first_name = Input::get('firstname');
            $data->last_name = Input::get('lastname');
            $data->password = Hash::make((Input::get('password')));
            $data->status_id = 1;
            $data->role = 'operator';
            $data->save();
            // redirect
            return Response::json(["redirect_to" => "alert_messages"]);
        } else {
            if (Request::ajax()) {
                $response_values = array(
                    'validation_failed' => 1,
                    'errors' => $validation->errors()->toArray(),
                );
                return Response::json($response_values);
            }
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return Response
     */
    public function show($id) {
        //
    }

    /**
     * The edit form of pending users status.
     *
     * @param  int  $id
     * @return Response
     */
    public function edit($id) {
        $values = DB::select('select * from users where id = ?', array($id));
        return View::make('pages.pending_edit', array(
                    'values' => $values,
        ));
    }

    /**
     * The edit form of users roles.
     *
     * @param  int  $id
     * @return Response
     */
    public function edit_roles($id) {
        $values = DB::select('select * from users where id = ?', array($id));
        return View::make('pages.roles_edit', array(
                    'values' => $values,
        ));
    }

    /**
     * Update the  status of users.
     *
     * @param  int  $id
     * @return Response
     */
    public function update($id) {
        $user = User::find($id);
        $user->status_id = Input::get('status');
        $user->save();
        return Response::json(["redirect_to" => "/users/pending"]);
    }

    /**
     * Update the  role of users.
     *
     * @param  int  $id
     * @return Response
     */
    public function update_roles($id) {
        $user = User::find($id);
        $user->role = Input::get('role');
        $user->save();
        return Response::json(["redirect_to" => "/users/roles"]);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return Response
     */
    public function destroy($id) {
        //
    }

    /**
     * Display the pending users
     *
     * @param  int  $id
     * @return array
     */
    public function pending_users() {
        $pending_users = DB::select('select u.*,u.id as user_id, s.* '
                        . 'from users as u inner join status as s '
                        . 'on s.id=u.status_id '
                        . 'where status_id = 1');
        return View::make('pages.pending_users', array(
                    'pending' => $pending_users,
        ));
    }

    /**
     * Display all user's roles
     *
     * @return array
     */
    public function users_roles() {
        $users_roles = DB::select('select * from users');
        return View::make('pages.users_roles', array(
                    'users_roles' => $users_roles,
        ));
    }

    /**
     * Login the user
     *
     * @return Response
     */
    public function doLogin() {
        Input::flash();
        $data = [
            "errors" => null
        ];
        $email = Input::get('email');
        $password = Input::get('password');
        if (!empty($email) && !empty($password)) {
            $status_id = DB::select('select status_id from users where email=?', array(Input::get('email'))
            );
            if ($status_id == NULL) {
                if (Request::ajax()) {
                    $response_values = array(
                        'validation_failed' => 1,
                        'errors' => Lang::get('login.invalid_login'),
                    );
                    return Response::json($response_values);
                }
            } else if ($status_id[0]->status_id == 1) {
                return Response::json(["redirect_to" => "alert_messages"]);
            } elseif ($status_id[0]->status_id == 2) {
                if (Auth::attempt(array('email' => Input::get('email'),
                            'password' => Input::get('password')))) {
                    return Response::json(["redirect_to" => "/"]);
                }
            }
        } else if ((!empty($email) && empty($password)) ||
                (empty($email) && !empty($password)) ||
                (empty($email) && empty($password)) ||
                (empty($email) && empty($password))) {
            if (Request::ajax()) {
                $response_values = array(
                    'validation_failed' => 1,
                    'errors' => Lang::get('login.invalid_login'),
                );
                return Response::json($response_values);
            }
        }
    }

    /**
     * Logot the user
     *
     * @return Response
     */
    public function doLogout() {
        Auth::logout();
        return Redirect::to('users');
    }

    /**
     * Login user with Google
     *
     * @return void
     */
    public function loginWithGoogle() {
        // get data from input
        $code = Input::get('code');

        // get google service
        $googleService = Artdarek\OAuth\Facade\OAuth::consumer("Google");

        if (!empty($code)) {

            // This was a callback request from google, get the token
            $token = $googleService->requestAccessToken($code);

            // Send a request with it
            $result = json_decode($googleService->request('https://www.googleapis.com/oauth2/v1/userinfo'), true);

            $user = User::whereEmail($result['email'])->first(['id']);
            if (empty($user)) {
                $data = new User;
                $data->Username = $result['name'];
                $data->email = $result['email'];
                $data->social_id = $result['id'];
                $data->first_name = $result['given_name'];
                $data->last_name = $result['family_name'];
                $data->status_id = 1;
                $data->role = 'operator';
                $data->save();
                return Redirect::to('alert_messages');
            } else {
                $status_id = DB::select('select status_id from users where id = ?', array($user->id));
                if ($status_id[0]->status_id == 1) {
                    return Redirect::to('alert_messages');
                } elseif ($status_id[0]->status_id == 2) {
                    Auth::login($user);
                    return Redirect::to('/');
                }
            }
        }
        // if not ask for permission first
        else {
            // get googleService authorization
            $url = $googleService->getAuthorizationUri();

            // return to facebook login url
            return Redirect::to((string) $url);
        }
    }

}
